import { reactive } from "vue";

export function useRequestList(API, PARAMS) {
  const REQUSET_LIST = reactive({
    loading: false,
    finished: false,
    refreshing: false,
    list: [],
    page: {
      pageNum: 1,
      pageSize: 20,
    },
    callBack: (call, args) => {
      typeof call === "function" && call(args);
    },
  });

  function onRefresh(request, params = {}, pagination = true, the_loading) {
    !pagination && the_loading && the_loading.show();
    // 清空列表数据
    REQUSET_LIST.finished = false;
    REQUSET_LIST.list = [];
    // 重新加载数据
    // 将 loading 设置为 true，表示处于加载状态
    REQUSET_LIST.loading = true;

    if (REQUSET_LIST.refreshing) {
      REQUSET_LIST.list = [];
      REQUSET_LIST.refreshing = false;
    }

    // setTimeout(() => {
    pagination
      ? ((REQUSET_LIST.page.pageNum = 1),
        onLoadListPage(request, { ...params, ...REQUSET_LIST.page }))
      : onLoadList(request, params, the_loading);
    // }, 1000);
  }

  async function queryData(request, params = {}) {
    try {
      const { data: { list, total } } = await request(params);
      REQUSET_LIST.list = [...REQUSET_LIST.list, ...list || []];
      REQUSET_LIST.loading = false;
      console.log(REQUSET_LIST.list.length, total)
      if (REQUSET_LIST.list.length >= +total) {
        REQUSET_LIST.finished = true;
      }
      REQUSET_LIST.page.pageNum++;
    } catch (e) {
      REQUSET_LIST.loading = false;
      REQUSET_LIST.finished = true;
    }
  }

  async function onLoadListPage(request, params = {}) {
    if (Array.isArray(request)) {
      REQUSET_LIST.loading = false;
      REQUSET_LIST.finished = true;
      REQUSET_LIST.list = [...request];
      return
    }
    if (request && typeof request == "function") {
      queryData(request, { ...params, ...REQUSET_LIST.page });
    } else {
      REQUSET_LIST.loading = false;
      REQUSET_LIST.finished = true;
      console.log("request 方法对象未找到");
    }
  }

  async function onLoadList(request, params = {}, the_loading) {
    try {
      REQUSET_LIST.loading = true;
      if (request && typeof request == "function") {
        const { data } = await request(params);
        REQUSET_LIST.list = data || [];
      }
    } catch (e) {
      console.log(e);
    } finally {
      REQUSET_LIST.loading = false;
      REQUSET_LIST.finished = true;
      the_loading && the_loading.close();
    }
  }

  return {
    REQUSET_LIST,
    onRefresh,
    queryData,
    onLoadList,
    onLoadListPage,
  };
}
